<template>
  <nut-overlay v-model:visible="isShow" :close-on-click-overlay="false" :overlay-style="{
    backgroundColor: 'rgba(0, 0, 0, .5)'
  }">
    <div class="login_pop" v-if="isShow">
      <div class="login">
        <p class="title_p">
          <span>{{ t(state.formData?.title) }}</span>
          <iconpark-icon class="close" icon-id="exit" color="#fff" size="1rem" @click="closeDialog"></iconpark-icon>
        </p>
        <div class="content">
          <div class="tab" v-if="state.formData?.tabList">
            <span :class="state.formData.active == tab.value ? 'active_tab' : ''"
              v-for="(tab, i) in state.formData.tabList" :key="i" @click="changeTab(tab.value, tab)">{{
                t(tab.name) }}</span>
          </div>

          <nut-form ref="formRef" label-position="top" :model-value="state.formData?.formParams"
            :show-label="state.formData?.showLabel">
            <template v-for="(item, i)  in state.formData?.list ">

              <div style="font-size: 12px;margin-bottom: 8px;color: #fff;" v-if="item.subtitle && item.show">{{
                item.subtitle }}
              </div>
              <nut-form-item :label="t(item.label)" v-if="item.show" :prop="item.name"
                :rules="state.formData?.rules[item.name]" :key="i">

                <nut-input clearable :type="item.type" v-model="state.formData.formParams[item.name]"
                  :disabled="item.disabled" @blur="blurValidate(item.name)"
                  @update:model-value="changeValidate(item.name)" :placeholder="t(item.placeholder)">
                  <template #left v-if="item.leftIcon && item.isMobile">
                    <span v-if="item.isMobile" style="color:#fff;margin-right: 10px;">+{{
                      state.formData.formParams.codeValue }}</span>
                  </template>
                  <template #right v-if="item.changeRightIcon">
                    <span @click="iconClick(item)" v-if="item.changeRightIcon"
                      style="color: #8e82c2!important;font-size: 18px!important;">
                      <iconpark-icon v-if="item.type == 'password'" name="hide" color="#8e82c2"
                        size="1rem"></iconpark-icon>
                      <iconpark-icon v-if="item.type == 'text'" name="eye12" color="#8e82c2"
                        size="1rem"></iconpark-icon>
                    </span>
                  </template>
                </nut-input>
                <span @click="submitSend(item)" v-if="item.name == 'captcha'" class="btn">
                  <ImgT :src="state.captchaURL" v-if="state.captchaURL" alt="" />
                  <iconpark-icon icon-id="signicon08" color="#fff" size="1.5rem"></iconpark-icon>
                </span>
                <nut-button :bordered="false" :loading="item.loading" @click="submitSend(item)"
                  v-if="item.slot && item.type == 'code'" class="btn btn_inline" :disabled="item.btnDisabled">{{
                    isNaN(item.timeText) ? t(item.timeText) : item.timeText
                  }}</nut-button>
              </nut-form-item>
            </template>
          </nut-form>

          <div style="margin-top: 16px">
            <nut-button :loading="props.loading" class="btn_block" round block @click="submitNext">
              {{ t(state.formData?.buttonText) }}
            </nut-button>
          </div>

        </div>
      </div>
    </div>

  </nut-overlay>

  <Modal v-model:visible="SMSModal" :title="t('home_page_smsTitle')">
    <div class="tips">
      <p>{{ t('home_page_smsContent') }}<b>{{ t('home_page_smsPrice') }}</b>{{ t('home_page_smsContent1') }}
      </p>
      <p style="margin-top:24px">{{ t('home_page_smsContent2') }} <span
          @click="changeTab(state.formData?.tabList[2].value, state.formData?.tabList[2])">{{
            t('contactService')
          }}</span></p>
      <nut-button style="margin-top:24px" class="btn_block" :bordered="false" block @click="sendMobileSmsCode"> {{
        t('home_page_confirm')
      }}</nut-button>
    </div>
  </Modal>
</template>

<script setup lang="ts">
import { MessageEvent2 } from "@/net/MessageEvent2";
import H5Websocket from "@/net/Net1";
import { NetMsgType } from "@/netBase/NetMsgType";
import { NetPacket } from "@/netBase/NetPacket";
import { ref, reactive } from "vue";
import { showNotify } from '@nutui/nutui'
import { useI18n } from 'vue-i18n';
const { t } = useI18n();


const props: any = defineProps({
  loading: {
    type: Boolean,
    deafult: false,
  }
})

const SMSModal = ref(false)
const emit = defineEmits(['changeTab', 'submitData', 'nextChange', 'onClose']);
const formRef = ref();
const isShow = ref(false)
const state: any = reactive({
  itemClick: null,
  formData: null,
  type: 0,
  codeOptions: [
    {
      label: '84',
      value: '84'
    },
  ],

})

const iconClick = (a: any) => {
  if (a.type == "password") {
    a.type = "text"
  } else {
    a.type = "password"
  }
};
const blurValidate = (name: string) => {
  formRef.value?.validate(name).then()
}
const changeValidate = (name: string) => {
  if (['mobile', 'email', 'new_password_confirm'].includes(name)) {
    formRef.value?.validate(name).then()
  }
}
const changeTab = (tabId: number, item: any) => {
  if (!item.isLink) {
    resetInputHide()
  }
  state.formData.formParams = state.formInitValue
  emit('changeTab', tabId, state.formData);

};
const resetInputHide = () => {
  for (const key in state.formData.list) {
    state.formData.list[key].show = false
  }
}


const submitNext = () => {
  // 效验
  if (state.type == 3) {
    formRef.value?.validate().then(({ valid, errors }: any) => {
      if (valid) {
        if (state.formData.step == 1) {
          emit('nextChange', state.formData.formParams);
        } else {
          emit('submitData', state.formData.formParams, state.type);
        }
      } else {
        console.log(errors);
      }
    });

  } else {
    //常规修改密码
    formRef.value?.validate().then(({ valid, errors }: any) => {
      if (valid) {
        emit('submitData', state.formData.formParams, state.type);
      } else {
        console.log(errors);
      }
    });
  }
};

// 手机验证码协议
const sendMobileSmsCode = () => {
  state.itemClick.loading = true
  SMSModal.value = false
  if (state.formData.forgetPassword) {
    const req = NetPacket.req_get_mobile_sms_login_code()
    req.mobile = state.formData.formParams.codeValue + state.formData.formParams.mobile
    H5Websocket.sendMessageHandler(req)
  } else {
    const req = NetPacket.req_get_mobile_sms_code()
    req.mobile = state.formData.formParams.codeValue + state.formData.formParams.mobile
    if (state.formData.list.mobile.disabled) {
      req.operate_type = 3
    } else {
      req.operate_type = 1
    }
    H5Websocket.sendMessageHandler(req)
  }
}

// 发送验证码
const submitSend = (item: any) => {
  state.itemClick = item
  // 1 为手机  2 为邮箱 
  if (state.formData.active == 1) {
    formRef.value?.validate('mobile').then(({ valid, errors }: any) => {
      if (valid) {
        SMSModal.value = true
      } else {
        console.warn('error:', errors)
      }
    })
  }
  if (state.formData.active == 2) {
    formRef.value?.validate('email').then(({ valid, errors }: any) => {
      if (valid) {
        item.loading = true
        const req = NetPacket.req_get_email_verification_code()
        req.email = state.formData.formParams.email
        H5Websocket.sendMessageHandler(req)
      } else {
        console.warn('error:', errors)
      }
    })
  }
};


// 邮箱验证码发送结果
const handleEmailback = (res: any) => {
  state.formData.list.emailCode.loading = false
  if (res.code == 1) {
    if (res.message) {
      showNotify.success(t(res.message))
    }
    state.formData.list.emailCode.btnDisabled = true
    state.formData.list.emailCode.timeText = 180
    setTimeout(() => {
      state.formData.list.emailCode.loading = false
    }, 300)
    state.formData.list.emailCode.timer = setInterval(() => {
      state.formData.list.emailCode.timeText--
      if (state.formData.list.emailCode.timeText <= 0) {
        clearInterval(state.formData.list.emailCode.timer)
        state.formData.list.emailCode.btnDisabled = false
        state.formData.list.emailCode.timer = null
        state.formData.list.emailCode.timeText = 'get_verification_code'
      }
    }, 1000);
  }


}
// 返回修改密码手机验证码是否发送
const handleSMSback = (res: any) => {
  state.formData.list.phoneCode.loading = false
  if (res.code == 1) {
    if (res.message) {
      showNotify.success(t(res.message))
    }
    state.formData.list.phoneCode.btnDisabled = true
    state.formData.list.phoneCode.timeText = 180
    setTimeout(() => {
      state.formData.list.phoneCode.loading = false
    }, 300)
    state.formData.list.phoneCode.timer = setInterval(() => {
      state.formData.list.phoneCode.timeText--
      if (state.formData.list.phoneCode.timeText <= 0) {
        clearInterval(state.formData.list.phoneCode.timer)
        state.formData.list.phoneCode.btnDisabled = false
        state.formData.list.phoneCode.timer = null
        state.formData.list.phoneCode.timeText = 'get_verification_code'
      }
    }, 1000);
  }

}

// 关闭弹窗
const closeDialog = () => {
  isShow.value = false
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_email_verification_code, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_mobile_sms_code, null);
  if (state.formData.list?.emailCode) {

    clearInterval(state.formData.list?.emailCode?.timer)
    state.formData.list.emailCode.disabled = true
    state.formData.list.emailCode.timer = null
    state.formData.list.emailCode.timeText = 'get_verification_code'
  }
  if (state.formData.list?.phoneCode?.timer) {
    clearInterval(state.formData.list.phoneCode.timer)
    state.formData.list.phoneCode.disabled = true
    state.formData.list.phoneCode.timer = null
    state.formData.list.phoneCode.timeText = 'get_verification_code'
  }
  console.log(state.formData?.formParams);
  emit('onClose')
  state.formData.formParams = state.formInitValue

};
// 打开弹窗
const openDialog = async (formData: any, type: number) => {
  state.formData = formData//JSON.parse(JSON.stringify(formData)) //
  state.formInitValue = JSON.parse(JSON.stringify(formData.formParams))
  state.type = type
  // 监听手机号验证码返回
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_get_mobile_sms_code,
    handleSMSback
  );
  // 监听邮箱验证码返回
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_get_email_verification_code,
    handleEmailback
  );
  // 监听忘记密码手机号验证码返回
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_nodify_get_mobile_sms_login_code,
    handleSMSback
  );

  isShow.value = true
}

defineExpose({
  openDialog,
  closeDialog,
});

</script>
<style lang="scss" scoped>
.login_pop {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login {
  border-radius: 16px;
  background: #131232;
  box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;
  width: 347px;

  :deep(.nut-input-value) {
    border-radius: 8px;
    background: #1D1C3C;
    box-shadow: 0.5px 0.5px 1px 0px #333260 inset;
    height: 48px;
    line-height: 48px;
    padding: 0 14px;
  }


  :deep(.nut-form-item) {
    padding: 0 0 14px 0 !important;

    .nut-cell__title {
      display: none !important;
    }
  }

  :deep(.nut-cell-group__wrap) {
    box-shadow: none;
    margin: 0;
  }

  :deep(.nut-form-item__body__slots) {
    display: flex;
  }

  :deep(.nut-cell-group .nut-cell::after) {
    border: none;
  }

  :deep(.nut-form-item.error.line::before) {
    border: none;
  }

  :deep(.nut-input-right-box) {
    position: relative;
  }

  :deep(.input-text) {
    &::placeholder {
      color: #504F6F !important;
    }
  }

  .title_p {
    border-bottom: 0.5px solid #242352;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #FFF;
    font-size: 16px;
    font-weight: 500;
    line-height: 16px;
    position: relative;

    .close {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 20px;
      color: #fff;
      font-size: 20px;
    }
  }

  .content {
    padding: 20px 20px 32px 20px;

    .tab {
      width: 300px;
      margin: 0 auto 20px auto;
      display: flex;
      justify-content: space-around;
      align-items: center;
      border-radius: 8px;
      background: #0B0B23;

      >span {
        width: 100px;
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #504F6F;
        font-size: 14px;
        font-weight: 400;
      }

      .active_tab {
        border-radius: 8px;
        background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
        box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;
        color: #fff;
        font-weight: 500;
        margin: 2px;
      }
    }
  }

  .btn {
    min-width: 110px;
    height: 44px;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    border-radius: 8px !important;
    overflow: hidden;
    // position: relative;
    // left: 12px;
    margin-left: 10px;
    background-color: #0F052A;

    >img {
      width: 100%;
      height: 100%;
    }
  }

  .btn_block {
    border-radius: 8px !important;
    background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
    box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;
    height: 44px;
    margin-top: 10px;
  }



}

.tips {
  text-align: start;
  padding: 24px 20px 30px 20px !important;

  p {
    color: #FFF;
    font-family: "PingFang SC";
    font-size: 14px;
    font-style: normal;
    font-weight: 500;
    line-height: 21px;
    /* 150% */

    >b {
      color: #ED8302;
    }

    >span {
      color: #E43939;
      cursor: pointer;
    }
  }
}
</style>
